package com.fisher.IdempotentDemo.interceptor;

import cn.hutool.json.JSONUtil;
import com.fisher.IdempotentDemo.annotation.AutoIdempotent;
import com.fisher.IdempotentDemo.model.vo.ResultVo;
import com.fisher.IdempotentDemo.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;

/**
 * @author ：fisher wu
 * @date ：Created in 2021/11/23 9:48 上午
 * @description：拦截器
 */
@Component
public class AutoIdempotentInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    /**
     * 预处理
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 查找被AutoIdempotent标记的方法
        AutoIdempotent methodAnnotation = method.getAnnotation(AutoIdempotent.class);
        if (methodAnnotation != null) {
            try {
                return tokenService.checkToken(request);
            } catch (Exception e) {
                ResultVo failedResult = new ResultVo(101L, e.getMessage());
                writeReturnJson(response, JSONUtil.toJsonStr(failedResult));
            }
        }
        return true;
    }

    private void writeReturnJson(HttpServletResponse response, String json) throws Exception {
        OutputStream os = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");

        try {
            os = response.getOutputStream();
            os.write(json.getBytes(StandardCharsets.UTF_8));
            os.flush();
        } catch (IOException e) {
        } finally {
            if (os != null) {
                os.close();
            }
        }
    }

}
